<?php

namespace cms\modules\v1\models\user;

use cms\modules\v1\models\Common;
use common\models\Functions;
use common\models\im\Im;
use common\models\prop\PropUserWarehouse;
use common\models\Status;
use common\models\user\User;
use Yii;
use yii\base\Exception;

/**
 * Class User
 * @package cms\modules\v1\models
 */
class UserUnusualLog extends \common\models\user\UserUnusualLog
{
    /**
     * 返回列表数据
     * @param int $page
     * @param int $size
     * @param array $search
     * @return array
     */
    public function getListData($page = 1, $size = 20, $search = [])
    {
        try {

            //搜索条件
            $searchWhere = $this->getSearch($search);//自定义搜索条件

            //得到文章的总数
            if (isset($searchWhere['andWhere'])) {
                $count = self::getCountByAndWhere($searchWhere['where'], $searchWhere['andWhere']);
            } else {
                $count = self::getCountByWhere($searchWhere);
            }
            $data = static::setPageinationAPI($page, $size, $count);

            //设置分页
            $offset = ($data['page'] - 1) * $size;

            //排序 order
            $orderSql = 'id DESC';

            if (isset($searchWhere['andWhere'])) {
                $list = static::getByAndWhere($searchWhere['where'], $searchWhere['andWhere'], '*', $orderSql, $offset, $size);
            } else {
                $list = static::getByWhere($searchWhere, '*', $orderSql, $offset, $size);
            }

            $data['data'] = $this->handelList($list);

            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 自定义参数的搜索  搜索,搜索也分每一列
     * 这里要根据业务逻辑进行修改
     * @param array $search
     * @return array
     */
    public function getSearch($search = '')
    {
        $where = [];
        $andWhere = [];
        $search = json_decode($search, true);
        if (!empty($search)) {
            $status = isset($search['status']) ? $search['status'] : '';
            $type = isset($search['type']) ? $search['type'] : '';
            $loginName = isset($search['login_name']) ? trim($search['login_name']) : '';

            $startTime = isset($search['start']) ? $search['start'] : '';
            $endTime = isset($search['end']) ? $search['end'] : '';
            if ($loginName) {
                $userId = User::searchByName($loginName);
                $where['user_id'] = $userId;
            }

            if ($status) {
                $where['status'] = $status;
            }

            if ($type) {
                $where['type'] = $type;
            }

            if (!empty($startTime) && empty($endTime)) {
                $andWhere = ['>', 'create_time', $startTime];
            } elseif (empty($startTime) && !empty($endTime)) {
                $andWhere = ['<', 'create_time', $endTime];
            } elseif (!empty($startTime) && !empty($endTime)) {
                $andWhere = ['between', 'create_time', $startTime, $endTime];
            }
        }
        return [
            'where' => $where,
            'andWhere' => $andWhere
        ];
    }

    /**
     * 处理初始化数据
     * @param $list
     * @return mixed
     */
    public function handelList($list)
    {
        if (empty($list)) {
            return null;
        }
        $userIds = array_column($list, 'user_id');
        $userMap = User::getFormArray(['id' => $userIds], 'id', 'login_name');
        foreach ($list as $key => $value) {
            $list[$key]['user_id'] = $userMap[$value['user_id']] ?? '';
            $list[$key]['statusName'] = Status::USER_UNUSUAL_STATUS_MAP[$value['status']] ?? '';
            $list[$key]['unusual_type'] = Status::USER_UNUSUAL_TYPE_MAP[$value['type']] ?? '';
            $list[$key]['expire_time'] = $value['auto_normal_time'] ?: '';
            $list[$key]['reason'] = $value['reason'] ?: '';
        }
        return $list;
    }

    /**
     * 添加修改
     * @return array
     */
    public function addEdit()
    {
        $trans = Yii::$app->db->beginTransaction();
        try {
            $post = Yii::$app->request->post();
            $id = isset($post['id']) && !empty($post['id']) ? intval($post['id']) : 0;
            $data = [];

            if (empty($id)) {
                throw new Exception('请选择数据进行操作~~');
            }
            #
            $info = static::getOneInfoById($id);
            if(empty($info)){
                throw new Exception('未知数据~~');
            }

            //更新操作
            $data['handle_normal_time'] = date('Y-m-d H:i:s');
            $data['status'] = Status::USER_UNUSUAL_STATUS_NORMAL;
            $data['mark'] = trim($post['mark']);
            $res = static::updateDataWithLog($data, ['id' => $id]);
            if ($res === false) {
                throw new Exception('系统错误，请联系开发小哥哥~~');
            }

            if($info['type'] == Status::USER_UNUSUAL_TYPE_ALL){
                $userRes = User::updateData(['status' => Status::COMMON_RADIO_YES],['id' => $info['user_id']]);
                if ($userRes === false) {
                    throw new Exception('用户状态操作失败~~');
                }
            }

            // 如果是聊天封禁，需要修改IM信息
            if ($info['type'] == Status::USER_UNUSUAL_TYPE_CHAT) {
                $singUserInfo = User::getObjectByWhere(['id' => $info['user_id']],['id','tx_code','login_name'])->indexBy('id')->asArray()->one();
                if ($singUserInfo) {
                    // 更新用户信息
                    $updateImUser['Tag_Profile_Custom_jinyan'] = (string) Status::COMMON_RADIO_NO;
                    $resIm = (new Im()) -> updateUser($singUserInfo['tx_code'], $updateImUser);
                    if (!$resIm) {
                        throw new Exception('更新用户信息失败');
                    }
                }

            }

            $trans->commit();
            return Functions::formatRestAPI(0, '解封成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 获取修改信息
     * @param int $id
     * @return array
     */
    public function getInfo($id = 0)
    {
        try {
            $id = (int)$id;

            if (empty($id)) {
                throw new Exception('未知信息');
            }
            $info = static::getOneInfoById($id);
            if (empty($info)) {
                throw new Exception('信息不存在');
            }
            $result['user_id'] = User::getOneByField($info['user_id'], 'login_name');
            $result['unusual_type'] = Status::USER_UNUSUAL_TYPE_MAP[$info['type']] ?? '';
            $result['time'] = $info['create_time'];
            $result['type'] = $info['type'];
            $result['duration'] = $info['duration'];
            $result['auto_normal_time'] = $info['auto_normal_time'];
            $result['money'] = floatval($result['money']);
            return Functions::formatRestAPI(0, '', $result);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 封禁
     * @return array
     * @throws \yii\db\Exception
     */

    public function saveUnusual() {
        $trans = Yii::$app->db->beginTransaction();
        try{
            $id = Yii::$app->request->post('id','');
            $type = Yii::$app->request->post('type','');
            $duration = Yii::$app->request->post('duration','');
            $reason = Yii::$app->request->post('reason','');
            if (empty($id) || empty($type) || empty($duration) || empty($reason)){
                throw new Exception('缺少参数');
            }

            if (!is_array($id)) {
                $ids = [$id];
            } else {
                $ids = $id;
            }

            $userMap = User::getObjectByWhere(['id' => $ids],['id','tx_code','login_name'])->indexBy('id')->asArray()->all();

            foreach ($ids as $v) {

                $unusual = static::getOneByWhere(['user_id' => $v,'status' => Status::USER_UNUSUAL_STATUS_UNUSUAL,'type' => $type]);
                if($unusual){
                    throw new Exception('该用户正在封禁中');
                }

                if($type == Status::USER_UNUSUAL_TYPE_ALL){
                    User::updateData([
                        'status' => Status::COMMON_RADIO_NO,
                        'access_token' => null,
                    ],['id' => $v]);
                    $singUserInfo = $userMap[$v] ?? [];
                    if ($singUserInfo) {
                        $res = (new Im()) ->loginOut($singUserInfo['tx_code']);
                        if (!$res) {
                            throw new Exception('禁用失败');
                        }
                    }
                }

                static::disableUser($v, $type, $duration, $reason);

                // 如果是聊天封禁，需要修改IM信息
                if ($type == Status::USER_UNUSUAL_TYPE_CHAT) {
                    $singUserInfo = $userMap[$v] ?? [];
                    if ($singUserInfo) {
                        // 更新用户信息
                        $updateImUser['Tag_Profile_Custom_jinyan'] = (string) Status::COMMON_RADIO_YES;
                        $resIm = (new Im()) -> updateUser($singUserInfo['tx_code'], $updateImUser);
                        if (!$resIm) {
                            throw new Exception('更新用户信息失败');
                        }
                    }

                }

            }

            $trans->commit();
            return Functions::formatRestAPI(0, '操作成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }
}
